function [acmat,covmat,stdv]=nanaccov(y,lagvec)
% ACCOV 
% Dealing with NAN data
% 
% function [acmat,covmat,stdv]=accov(y,lagvec)
% 
% y             [t n] 
% lagvec        vector of which lags to compute 
% acmat         cross-correlation 
% covmat        covariances
%
% Alejandro Justiniano (C) 4/20/2006 
% =======================================================================

% throw away time period where there are NAN in data
nanrows = (sum(isnan(y), 2) ~= 0); 
y(nanrows, :)  = []; 

[t,n]=size(y);
if t < n 
    warning('Number of series (Cols) exceeds number of observations (Rows)') 
end 

% AJ wants to comment out this part, to deal with small sample size
% if any(lagvec(:)>t-15)==1 
%     error('LAGVEC yields less than 15 observations') 
% end 
if any(lagvec(:) < 0)==1 
    warning('LAGVEC using LEADS not LAGS') 
end 
nlag=length(lagvec(:)); 
ydem=y-repmat(sum(y)/t,t,1); 
varm=ydem'*ydem/(t-1);
stdv=sqrt(diag(varm)); 
divmat=stdv*(stdv'); 
acmat=zeros(n,n,nlag); 
covmat=zeros(n,n,nlag); 
ii=1; 
for ii=1:nlag 
    p=lagvec(ii); 
    if p > 0 
        covmat(:,:,ii)=(ydem(p+1:end,:)')*ydem(1:end-p,:)/(t); 
    else 
        covmat(:,:,ii)=varm; 
    end 
    acmat(:,:,ii)=covmat(:,:,ii)./(divmat); 
end